package com.ly.datacenter.crud.json;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONObject;

import com.ly.datacenter.component.pager.pojo.Pager;
import com.ly.datacenter.pojo.KeyValue;

/**
 * function：
 * 
 * @author watson email: watson.wu@hotmail.com
 * @date 2009-9-4
 */
public class ReadJSON {

	private int page;
	private int total;// the sum of all pages
	private int records;// the sum of all records
	private List<Row> rows;

	public ReadJSON(Pager pager) {
		this.page = pager.getPage();
		this.total = pager.getTotalPages();
		this.records = pager.getTotalSize();
		List<List<KeyValue>> list = pager.getList();
		rows = new ArrayList<Row>();
		for(List<KeyValue>map:list) {
			rows.add(new Row(KeyValue.values(map), KeyValue.getValueOf(map, pager.getPk()).toString()));
		}
	}

	public ReadJSON(int page, int records, List<Row> rows, int total) {
		this.page = page;
		this.records = records;
		this.rows = rows;
		this.total = total;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public int getRecords() {
		return records;
	}

	public void setRecords(int records) {
		this.records = records;
	}

	public List<Row> getRows() {
		return rows;
	}

	public void setRows(List<Row> rows) {
		this.rows = rows;
	}

	public class Row {
		private String id;
		private List<String> cell;

		public Row(List<String> cell, String id) {
			this.cell = cell;
			this.id = id;
		}

		public Row(Collection<Object> values, String id) {
			this.id = id;
			cell = new ArrayList<String>();
			if(null != values) {
				Iterator<Object> iterator = values.iterator();
				while(iterator.hasNext()) {
					cell.add(iterator.next().toString());
				}
			}
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public List<String> getCell() {
			return cell;
		}

		public void setCell(List<String> cell) {
			this.cell = cell;
		}

		@Override
		public String toString() {
			JSONObject object = new JSONObject();
			object.put("id", id);
			object.put("cell", cell);
			return super.toString();
		}
	}

	@Override
	public String toString() {
		JSONObject object = new JSONObject();
		object.put("page", page);
		object.put("total", total);
		object.put("records", records);
		object.put("rows", rows);
		return object.toString();
	}

}